// @algorithm @lc id=100342 lang=cpp
// @title ping-heng-er-cha-shu-lcof

#include "algm/algm.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode *root) {
        int depth = 0;
        return isBalanced(root, depth);
    }
    // helper
    bool isBalanced(TreeNode *root, int &depth) {
        if (root == nullptr) {
            depth = 0;
            return true;
        }
        int left, right;
        if (isBalanced(root->left, left) && isBalanced(root->right, right)) {
            int diff = left - right;
            if (diff <= 1 && diff >= -1) {
                depth = 1 + (left > right ? left : right);
                return true;
            }
        }
        return false;
    }
};